﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using Aandelendelen.Mail;

namespace Aandelendelen.TextLinks
{
	public class TextLink
	{
		private int DaysToExpire
		{
			get { return (this.EndDate - DateTime.Today).Days; }
		}

		private int Duration
		{
			get { return (this.EndDate - this.StartDate).Days; }
		}

		private bool HasStarted
		{
			get { return ((DateTime.Today - this.StartDate).Days >= 0); }
		}

		private bool IsExpired
		{
			get { return (DaysToExpire <= 0); }
		}

		internal bool IsActive
		{
			get { return HasStarted && !IsExpired; }
		}

		internal void CheckExpired()
		{
			int daysLeft = DaysToExpire;

			if (daysLeft >= 0)
			{
				if (daysLeft == 7)
					NotifyAdvertiser(false);
				else if (daysLeft == 0)
					NotifyAdvertiser(true);
			}
		}

		private void NotifyAdvertiser(bool expired)
		{
			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			StringBuilder str = new StringBuilder(128);
			if (Prefix != null)
			{
				str.Append(Prefix);
				str.Append(" ");
			}

			str.Append(Text);

			if (Suffix != null)
			{
				str.Append(" ");
				str.Append(Suffix);
			}

			mailArgs["{aanhef}"] = "Geachte " + Name + ",";
			mailArgs["{startdate}"] = StartDate.ToLongDateString();
			mailArgs["{enddate}"] = EndDate.ToLongDateString();
			mailArgs["{text}"] = str.ToString();
			mailArgs["{link}"] = Href;

			EMail email = MailCache.GetMail(expired ? "textadexpired" : "textadexpiresinsevendays");
			email.Recipients = Email;

			email.QueueSingle();
		}

		public WebControl CreateWebControl()
		{
			Panel panel = new Panel();
			panel.CssClass = "sponsor";

			if (string.IsNullOrEmpty(this.Prefix) == false)
			{
				Label prefix = new Label();
				prefix.Text = this.Prefix;

				panel.Controls.Add(prefix);
			}

			HyperLink link = new HyperLink();
			link.Target = "_blank";
			link.NavigateUrl = this.Href;
			link.Text = this.Text;
			link.CssClass = "sponsor";

			if (this.NoFollow)
				link.Attributes["rel"] = "nofollow";

			panel.Controls.Add(link);

			if (string.IsNullOrEmpty(this.Suffix) == false)
			{
				Label suffix = new Label();
				suffix.Text = this.Suffix;

				panel.Controls.Add(suffix);
			}

			return panel;
		}

		public string Href { get; internal set; }
		public string Text { get; internal set; }
		public string Prefix { get; internal set; }
		public string Suffix { get; internal set; }
		public string Name { get; internal set; }
		public string Email { get; internal set; }
		public bool NoFollow { get; internal set; }
		public DateTime StartDate { get; internal set; }
		public DateTime EndDate { get; internal set; }
	}
}